




from flask import Flask, request, jsonify
import threading
from concurrent.futures import ThreadPoolExecutor
import queue
from checkUrlAccess import get_access
from page import page_info
app = Flask(__name__)
app.config['THREADING'] = True
result_queue = queue.Queue()

executor = ThreadPoolExecutor(max_workers=8)

@app.route('/api/data', methods=['GET'])
def get_data():
    name = request.args.get('name', default='', type=str)
    def handle_request(name):
        info = page_info(name)
        if info:
            data={
                'data': page_info(name),
                'code': 0,
                'status': True,
                'msg': '获取成功'
            }
        else:
            data = {
                'data': page_info(name),
                'code': 1,
                'status': False,
                'msg': '获取失败'
            }
        result_queue.put(jsonify(data))

    future = executor.submit(handle_request, name)

    # 从队列中获取结果并返回
    response = result_queue.get()
    return response


@app.route('/api/checkurl',methods=['GET'])
def get_checkUrl():
    id = request.args.get('id', default='', type=str)
    def handle_request(id):
        data = get_access(id)  # 假设这个函数返回一些数据
        print('类型',type(data))
        result_queue.put(jsonify(data))  # 将数据放入队列
    def thread_target():
        with app.app_context():
            handle_request(id)
    thread = threading.Thread(target=thread_target)
    thread.start()

    # 等待线程完成
    thread.join()

    # 从队列中获取结果并返回
    try:
        response = result_queue.get_nowait()  # 使用 get_nowait 来避免阻塞，或者使用 get 并设置超时
    except queue.Empty:
        response = jsonify({'error': 'No data available'})  # 如果队列为空，返回错误信息

    return response
if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8011, debug=False)